//
//  FontsDownloadManager.m
//  ebook
//
//  Created by mt on 16/9/14.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "FontsDownloadManager.h"
#import "EbookNetRequest.h"
#import "FontModel.h"

#define Path [NSString stringWithFormat:@"%@/%@", PATH_OF_DOCUMENT, @"Fonts"]

@interface FontsDownloadManager () {
    
    __block float lastpercent;
    __block BOOL isDownloading;
    __strong NSMutableArray *downloadQueue;
}

@end

@implementation FontsDownloadManager

+ (instancetype)shareInstance {
    
    static FontsDownloadManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[FontsDownloadManager alloc] init];
    });
    return manager;
}

- (instancetype)init {
    
    if (self = [super init]) {
        downloadQueue = [NSMutableArray array];
    }
    return self;
}

- (void)addDownloadFont:(FontModel *)download {
    
    [downloadQueue addObject:download];
    
    if (!isDownloading)
        [self startDownloadTask];
}

- (void)startDownloadTask {
    
    if (downloadQueue.count>0) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [self fontsDownloadWithFontModel:downloadQueue.firstObject];
        });
    }
}

- (NSArray *)currentDownloadQueue {
    
    return downloadQueue;
}

- (void)fontsDownloadWithFontModel:(FontModel *)model {
    
    if (!model) return;
    isDownloading = YES;
    __block FontsDownloadManager *weakSelf = self;
    [EbookNetRequest downloadFileWithURLString:model.downurl downloadFileProgress:^(NSProgress *downloadProgress) {
        __strong __typeof(self) strongSelf = weakSelf;
        [strongSelf sendProgressNotificition:model progress:downloadProgress.fractionCompleted];
    } saveToPath:Path downloadCompletionHandler:^(NSURL *filePath, NSError *error) {
        MTLog(@"fontsDownloadWithFontModel->responseObject:%@", filePath);
        isDownloading = NO;
        [downloadQueue removeObject:model];
        __strong __typeof(self) strongSelf = weakSelf;
        [strongSelf startDownloadTask];
        if(error){
            MTLog(@"fontsDownloadWithFontModel->error:%@", error);
            [downloadQueue removeObject:model];
            NSString *path = [Path stringByAppendingPathComponent:[model.downurl lastPathComponent]];
            [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
        }
    }];
}

- (void)sendProgressNotificition:(FontModel *)model progress:(float)progress
{
    if (progress>lastpercent+0.001f||lastpercent>0.99) {//只有进度差大于0.01时才更新界面，避免频繁更新占用主进程造成界面卡死(上次进度已经超过了0.99的继续)
        lastpercent = progress;
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary *dic = [NSDictionary dictionaryWithObjects:@[model, @(progress)] forKeys:@[@"model", @"progress"]];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDownloadFontsNotification object:dic];
        });
    }
}

@end
